package dao;

import java.math.BigDecimal;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import action.HibernateSessionFactory;

import entity.House;
import entity.Users;


public class UsersDao {

	@SuppressWarnings("unchecked")
	public Users findUser(Users user) {

		Users u=null;
		Session session = HibernateSessionFactory.getSession();
		Criteria criteria = session.createCriteria(Users.class);
		criteria.add(Restrictions.eq("name",user.getName()));
		criteria.add(Restrictions.eq("password",user.getPassword()));
		List<Object> list=criteria.list();
		if(list.size()==1){
		u =(Users) criteria.list().get(0);
		}
		session.close();
		return u;
		
	}

	public Users findById(Users user) {
		Session session = HibernateSessionFactory.getSession();
		Criteria criteria = session.createCriteria(Users.class);
		criteria.add(Restrictions.eq("name",user.getName()));
		criteria.add(Restrictions.eq("password",user.getPassword()));
		user = (Users)criteria.list().get(0);
		session.close();
		return user;
	}
	
	public void save(Users user){
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction().begin();
		user.setId(new BigDecimal(0));
		session.save(user);
		session.beginTransaction().commit();
		session.close();
		
	}
	
	public List<House> findAll(int pageNo,int pageSize,Users user){
		 int firstResultIndex = pageSize*(pageNo-1);
		 Session session = HibernateSessionFactory.getSession();
		 Transaction tx = session.getTransaction();
		 Criteria criteria = session.createCriteria(House.class);
		 criteria.add(Restrictions.eq("USER_ID",user.getId()));
		 criteria.setFirstResult(firstResultIndex);
		 criteria.setMaxResults(pageSize);
		 List<House> list=criteria.list();
		 session.close();
		return list;

	}

}
